package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQueryObject;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.swing.*;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentMongoRepository repository;

    public void save(StrategyComment comment) {
        //填充评论时间
        comment.setCreateTime(new Date());
        repository.save(comment);
    }

    public Object query(StrategyCommentQueryObject qo) {
        //注意: spring data 默认分页页数从0开始
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize() );
        Page<StrategyComment> page = repository.findByDetailId(qo.getDetailId(), pageable);
        return page;
    }

    public void commentThumbUp(String toId, Long fromId) {
        // 1) 根据评论id获取评论对象
        Optional<StrategyComment> op = repository.findById(toId);
        // 2) 获取当前这条评论的点赞集合 comment就是当前这条评论对象
        op.ifPresent(comment -> {
            List<Long> thumbuplist = comment.getThumbuplist();
            // 3) 判断集合里面有没有当前登录用户的id, 有就删除, 没有就添加
            if (thumbuplist.contains(fromId)) {
                //取消点赞
                thumbuplist.remove(fromId);
            }else{
                //点赞评论
                thumbuplist.add(fromId);
            }
            comment.setThumbupnum(thumbuplist.size());
            //把这条评论更新到mongoDB数据库里面, 有文档id就是更新, 没有就是新增
            repository.save(comment);
        });
    }

}
